//
//  W_LoginViewController.m
//  Go!
//
//  Created by 凌風 on 16/7/15.
//  Copyright © 2016年 凌风. All rights reserved.
//

#import "W_LoginViewController.h"
#import "W_RegistViewController.h"

#pragma mark -- 短信验证
#import <SMS_SDK/SMSSDK.h>

@interface W_LoginViewController () <UITextFieldDelegate>

@property (nonatomic, strong) UIButton *registBtn;/**< 注册按钮 */
@property (nonatomic, strong) UIButton *getCheckCodeBtn; /**< 获取验证码按钮 */
@property (nonatomic, strong) UIButton *loginBtn; /**< 登录按钮 */
@property (nonatomic, strong) UIButton *accountAndPasswordLoginBtn;/**< 账号密码登录按钮 */
@property (nonatomic, strong) UIView *bgView;/**< 背景视图 */
@property (nonatomic, strong) UITextField *phoneNumTextField; /**< 手机号输入框 */
@property (nonatomic, strong) UITextField *checkCodeTextField;/**< 验证码输入框 */
@property (nonatomic, strong) UIView *loginView; /**< 使用账号和密码登录 */
@property (nonatomic, strong) UITextField *accountTextField;/**< 账号输入框 */
@property (nonatomic, strong) UITextField *passwordTextField;/**< 密码输入框 */
@property (nonatomic, strong) UIButton *forgetPasswordBtn;/**< 忘记密码按钮 */

// 数据源
@property (nonatomic, strong) NSArray *thirdLoginBtnName;


- (void)initializeDataSource; /**< 初始化数据源 */
- (void)initializeUserInterface; /**< 初始化用户界面 */
@end

@implementation W_LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initializeDataSource];
    [self initializeUserInterface];
}

- (void)initializeDataSource {
    
    self.thirdLoginBtnName = @[@"qq", @"sina", @"wechat"];
    
}

- (void)initializeUserInterface {
    self.topTitle = @"短信验证登录";
//    self.view.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];
    
    // 将注册按钮添加到顶部自定义导航栏上
    [self.topView addSubview:self.registBtn];
    
    // 添加背景视图
    [self.view addSubview:self.bgView];
    // 添加手机号码输入框
    [self.bgView addSubview:self.phoneNumTextField];
    // 添加验证码输入框
    [self.bgView addSubview:self.checkCodeTextField];
    // 添加获取验证码按钮
    [self.bgView addSubview:self.getCheckCodeBtn];
    // 添加登录按钮
    [self.view addSubview:self.loginBtn];
    // 添加账号和密码登录按钮
    [self.view addSubview:self.accountAndPasswordLoginBtn];
    
    // 添加账号密码登录视图
    [self.view addSubview:self.loginView];
    
    // 第三方登录
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(Size_W(8), ScreenH - Size_H(100), ScreenW - Size_W(16), 0.5)];
    lineView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:lineView];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, Size_W(100), Size_H(40))];
    label.center = CGPointMake(ScreenW * 0.5, CGRectGetMidY(lineView.frame));
    label.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];
    label.text = @"第三方登录";
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:Font(14)];
    [self.view addSubview:label];
    
    CGFloat btnW = ScreenW / 3;
    
    [self.thirdLoginBtnName enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(Size_W(btnW * 0.375) + btnW * 0.875 * idx, CGRectGetMaxY(label.frame), btnW * 0.5, btnW * 0.5);
        btn.layer.masksToBounds = true;
        btn.layer.cornerRadius = btnW * 0.25;
        
        [btn setImage:[UIImage imageNamed:obj] forState:UIControlStateNormal];
        btn.tag = 1000 + idx;
        
        [btn addTarget:self action:@selector(respondsToThirdLoginBtn:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.view addSubview:btn];
    }];

    
}

#pragma mark -- 监听事件的回调方法
// 注册按钮的点击事件
- (void)respondsToRegistBtn:(UIButton *)sender {
    W_RegistViewController *registVc = [[W_RegistViewController alloc] init];
    
    [self presentViewController:registVc animated:true completion:nil];
}

// 获取验证码按钮的点击事件
- (void)respondsToGetCheckCodeBtn:(UIButton *)sender {
    /**
     *  @from                    v1.1.1
     *  @brief                   获取验证码(Get verification code)
     *
     *  @param method            获取验证码的方法(The method of getting verificationCode)
     *  @param phoneNumber       电话号码(The phone number)
     *  @param zone              区域号，不要加"+"号(Area code)
     *  @param customIdentifier  自定义短信模板标识 该标识需从官网http://www.mob.com上申请，审核通过后获得。(Custom model of SMS.  The identifier can get it  from http://www.mob.com  when the application had approved)
     *  @param result            请求结果回调(Results of the request)
     */
    
    [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:self.phoneNumTextField.text
                                   zone:@"86"
                       customIdentifier:nil
                                 result:^(NSError *error){
                                     if (!error) {
                                         NSLog(@"获取验证码成功");
                                         
                                         [Tools showAlertWithMessage:@"获取验证码成功" ViewController:self];
                                         
                                     } else {
                                         NSLog(@"错误信息：%@",error);
                                     }
                                 }];
    sender.enabled = false;
}

// 手机号输入框的监听事件
- (void)respondsToPhoneNumTextField:(UITextField *)sender {
    if (sender.text.length == 11) {
        [self.getCheckCodeBtn setEnabled:true];
    } else {
        [self.getCheckCodeBtn setEnabled:false];
    }
}

// 验证码输入框的监听事件
- (void)respondsToCheckCodeTextField:(UITextField *)sender {
    if (sender.text.length > 0) {
        self.loginBtn.selected = true;
        [self.loginBtn setBackgroundColor:[UIColor redColor]];
    } else {
        
        self.loginBtn.selected = false;
        [_loginBtn setBackgroundColor:[UIColor colorWithWhite:0.85 alpha:1]];   
    }
}

// 登录按钮的点击事件
- (void)respondsToLoginBtn:(UIButton *)sender {
    if ([self.topTitle isEqualToString:@"短信验证登录"]) {
        if (self.phoneNumTextField.text.length == 0) {
            [Tools showAlertWithMessage:@"请输入手机号码" ViewController:self];
            return;
        }
        
        if (self.checkCodeTextField.text.length == 0) {
            [Tools showAlertWithMessage:@"请输入验证码" ViewController:self];
            return;
        }
        
        [SMSSDK commitVerificationCode:self.checkCodeTextField.text phoneNumber:self.phoneNumTextField.text zone:@"86" result:^(NSError *error) {
            
            if (!error) {
                NSLog(@"验证成功");
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"postUserInfo" object:@{@"userName":self.phoneNumTextField.text} userInfo:@{@"user":@"loginVc"}];
                
            }
            else
            {
                NSLog(@"错误信息:%@",error);
            }
        }];
    } else {
        if (self.accountTextField.text.length == 0) {
            [Tools showAlertWithMessage:@"请输入手机号码" ViewController:self];
            return;
        }
        
        if (self.passwordTextField.text.length == 0) {
            [Tools showAlertWithMessage:@"请输入验证码" ViewController:self];
            return;
        }
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"postUserInfo" object:@{@"userName":self.accountTextField.text} userInfo:@{@"user":@"loginVc"}];
    }
    
    [self dismissViewControllerAnimated:true completion:nil];
    
}

// 账号密码登录按钮的点击事件
- (void)respondsToAccountAndPasswordLoginBtn:(UIButton *)sender {
    
    self.loginBtn.selected = false;
    [_loginBtn setBackgroundColor:[UIColor colorWithWhite:0.85 alpha:1]];
    
    if (!sender.selected) {
        self.topTitle = @"账号和密码登陆";
        [UIView animateWithDuration:0.5f animations:^{
            // 切换登陆方式时，清空TextField
            self.accountTextField.text = @"";
            self.passwordTextField.text = @"";
            
            // 切换登陆方式视图
            self.loginView.center = CGPointMake(self.view.center.x, self.loginView.center.y);
            self.bgView.center = CGPointMake(ScreenW * 1.5, self.bgView.center.y);
            self.accountAndPasswordLoginBtn.selected = true;
            
        } completion:^(BOOL finished) {
            
        }];
    } else {
        self.topTitle = @"短信验证登陆";
        [UIView animateWithDuration:0.5f animations:^{
            // 切换登陆方式时，清空TextField
            self.phoneNumTextField.text = @"";
            self.checkCodeTextField.text = @"";
            
            // 切换登陆方式视图
            self.loginView.center = CGPointMake(-self.view.center.x, self.loginView.center.y);
            self.bgView.center = CGPointMake(self.view.center.x, self.bgView.center.y);
            self.accountAndPasswordLoginBtn.selected = false;
        } completion:^(BOOL finished) {
            
        }];
    }
    
}

// 当账号和密码都有值显示登陆按钮
- (void)respondsToShowLoginButton:(UITextField *)textField {
    if (self.accountTextField.text.length > 0 && self.passwordTextField.text.length > 0) {
        self.loginBtn.selected = true;
        [self.loginBtn setBackgroundColor:[UIColor redColor]];
    } else {
        self.loginBtn.selected = false;
        [_loginBtn setBackgroundColor:[UIColor colorWithWhite:0.85 alpha:1]];
    }
}

// 三方登陆按钮的点击事件
- (void)respondsToThirdLoginBtn:(UIButton *)sender {
    if (sender.tag == 1001) {
        [ShareSDK getUserInfo:SSDKPlatformTypeSinaWeibo onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error) {
            
            if (state == SSDKResponseStateSuccess) {
                NSLog(@"uid=%@",user.uid);
                NSLog(@"%@",user.credential);
                NSLog(@"token=%@",user.credential.token);
                NSLog(@"nickname=%@",user.nickname);
                NSLog(@"icon = %@", user.icon);
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"postUserInfo" object:@{@"userName":user.nickname, @"icon":user.icon} userInfo:@{@"user":@"thirdlogin"}];
                
                [self dismissViewControllerAnimated:true completion:nil];
                
            } else {
                NSLog(@"%@", error);
            }
            
        }];
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.phoneNumTextField resignFirstResponder];
    [self.checkCodeTextField resignFirstResponder];
}

#pragma mark -- UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([textField.placeholder isEqualToString:@"请输入手机号"]) {
        
        if (range.location > 10) {
            
            return false;
        }
    }
    
    return true;
}

#pragma mark -- Getter
- (UIButton *)registBtn {
    if (!_registBtn) {
        _registBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _registBtn.frame = CGRectMake(ScreenW - Size_W(48), 20 + Size_H(44 - 40) / 2, Size_W(40), Size_H(40));
        
        [_registBtn setTitle:@"注册" forState:UIControlStateNormal];
        [_registBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        _registBtn.titleLabel.font = [UIFont systemFontOfSize:Font(17)];
        
        [_registBtn addTarget:self action:@selector(respondsToRegistBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _registBtn;
}

- (UIButton *)getCheckCodeBtn {
    if (!_getCheckCodeBtn) {
        _getCheckCodeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _getCheckCodeBtn.frame = CGRectMake(ScreenW - Size_W(108), Size_H(8), Size_W(100), Size_H(34));
        [_getCheckCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        _getCheckCodeBtn.titleLabel.font = [UIFont systemFontOfSize:Font(17)];
        
        [_getCheckCodeBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [_getCheckCodeBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
        [_getCheckCodeBtn setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
        [_getCheckCodeBtn setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
        
        _getCheckCodeBtn.enabled = false;
        
        [_getCheckCodeBtn addTarget:self action:@selector(respondsToGetCheckCodeBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _getCheckCodeBtn;
}

- (UIButton *)loginBtn {
    if (!_loginBtn) {
        _loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _loginBtn.frame = CGRectMake(Size_W(8), CGRectGetMaxY(self.bgView.frame) + Size_H(8), ScreenW - Size_W(16), Size_H(44));
        [_loginBtn setTitle:@"登 录" forState:UIControlStateNormal];
        _loginBtn.titleLabel.font = SystemFont;
        
        // title颜色
        [_loginBtn setTitleColor:[UIColor colorWithWhite:0.65 alpha:1] forState:UIControlStateNormal];
        [_loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        
        // 背景色
        [_loginBtn setBackgroundColor:[UIColor colorWithWhite:0.85 alpha:1]];
        
        [_loginBtn addTarget:self action:@selector(respondsToLoginBtn:) forControlEvents:UIControlEventTouchUpInside];
        
        
    }
    
    return _loginBtn;
}

- (UIButton *)accountAndPasswordLoginBtn {
    if (!_accountAndPasswordLoginBtn) {
        _accountAndPasswordLoginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _accountAndPasswordLoginBtn.frame = CGRectMake(ScreenW - Size_W(115), CGRectGetMaxY(self.loginBtn.frame) + Size_H(8), Size_W(110), Size_H(25));
        [_accountAndPasswordLoginBtn setTitle:@"账号和密码登录" forState:UIControlStateNormal];
        [_accountAndPasswordLoginBtn setTitle:@"短信验证登陆" forState:UIControlStateSelected];
        _accountAndPasswordLoginBtn.titleLabel.textAlignment = NSTextAlignmentRight;
        _accountAndPasswordLoginBtn.titleLabel.font = [UIFont systemFontOfSize:Font(15)];
        [_accountAndPasswordLoginBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        
        [_accountAndPasswordLoginBtn addTarget:self action:@selector(respondsToAccountAndPasswordLoginBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _accountAndPasswordLoginBtn;
}

- (UIView *)bgView {
    if (!_bgView) {
        _bgView = ({
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.topView.frame) + Size_H(10), ScreenW, Size_H(101))];
            
            view.backgroundColor = [UIColor whiteColor];
            
            
            UIImageView *phoneNumImageView = [[UIImageView alloc] initWithFrame:CGRectMake(Size_W(8), Size_H(8), Size_W(34), Size_H(34))];
            
            phoneNumImageView.image = [UIImage imageNamed:@"手机.png"];
            
            [view addSubview:phoneNumImageView];
            
            
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(phoneNumImageView.frame) + Size_H(8), ScreenW, Size_H(0.5))];
            lineView.backgroundColor = [UIColor lightGrayColor];
            
            [view addSubview:lineView];
            
            UIImageView *checkCodeImageView = [[UIImageView alloc] initWithFrame:CGRectMake(Size_W(8), CGRectGetMaxY(lineView.frame) + Size_H(8), Size_W(34), Size_H(34))];
            
            checkCodeImageView.image = [UIImage imageNamed:@"验证码.png"];
            
            [view addSubview:checkCodeImageView];
            
            view;
        });
    }
    
    return _bgView;
}

- (UITextField *)phoneNumTextField {
    if (!_phoneNumTextField) {
        _phoneNumTextField = ({
            UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(Size_W(50), Size_H(8), CGRectGetMinX(self.getCheckCodeBtn.frame) - Size_W(50), Size_H(34))];
            
//            textField.placeholder = @"请输入手机号";
            textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入手机号" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:Font(17)]}];
            
            textField.delegate = self;
            
            textField.clearButtonMode = UITextFieldViewModeWhileEditing;
            textField.tintColor = [UIColor redColor];
            textField.keyboardType = UIKeyboardTypePhonePad;
            
            [textField addTarget:self action:@selector(respondsToPhoneNumTextField:) forControlEvents:UIControlEventEditingChanged];
            
            textField;
        });
    }
    
    return _phoneNumTextField;
}

- (UITextField *)checkCodeTextField {
    if (!_checkCodeTextField) {
        _checkCodeTextField = ({
            UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(Size_W(50), Size_H(58.5), ScreenW - Size_W(50), Size_H(34))];
            
            textField.placeholder = @"请输入短信中的验证码";
            textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入短信中的验证码" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:Font(17)]}];
            
            textField.delegate = self;
            
            textField.clearButtonMode = UITextFieldViewModeWhileEditing;
            textField.tintColor = [UIColor redColor];
            textField.keyboardType = UIKeyboardTypePhonePad;

            [textField addTarget:self action:@selector(respondsToCheckCodeTextField:) forControlEvents:UIControlEventEditingChanged];
            
            textField;
        });
    }
    
    return _checkCodeTextField;
}

- (UIView *)loginView {
    if (!_loginView) {
        _loginView = ({
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(-ScreenW, CGRectGetMaxY(self.topView.frame) + Size_H(10), ScreenW, Size_H(101))];
            
            view.backgroundColor = [UIColor whiteColor];
            
            
            UIImageView *phoneNumImageView = [[UIImageView alloc] initWithFrame:CGRectMake(Size_W(8), Size_H(8), Size_W(34), Size_H(34))];
            
            phoneNumImageView.image = [UIImage imageNamed:@"账号.png"];
            
            [view addSubview:phoneNumImageView];
            
            
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(phoneNumImageView.frame) + Size_H(8), ScreenW, Size_H(0.5))];
            lineView.backgroundColor = [UIColor lightGrayColor];
            
            [view addSubview:lineView];
            
            UIImageView *checkCodeImageView = [[UIImageView alloc] initWithFrame:CGRectMake(Size_W(8), CGRectGetMaxY(lineView.frame) + Size_H(8), Size_W(34), Size_H(34))];
            
            checkCodeImageView.image = [UIImage imageNamed:@"密码.png"];
            
            [view addSubview:checkCodeImageView];
            
            [view addSubview:self.accountTextField];
            [view addSubview:self.passwordTextField];
            
            view;
        });
    }
    
    return _loginView;
}

- (UITextField *)accountTextField {
    if (!_accountTextField) {
        _accountTextField = ({
            UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(Size_W(50), Size_H(8), ScreenW - Size_W(50), Size_H(34))];
            
            //            textField.placeholder = @"请输入手机号";
            textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入账号" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:Font(17)]}];
            
            textField.delegate = self;
            
            textField.clearButtonMode = UITextFieldViewModeWhileEditing;
            textField.tintColor = [UIColor redColor];
            textField.keyboardType = UIKeyboardTypePhonePad;
            textField.tag = 1004;
            [textField addTarget:self action:@selector(respondsToShowLoginButton:) forControlEvents:UIControlEventEditingChanged];
            
            textField;
        });
    }
    
    return _accountTextField;
}

- (UITextField *)passwordTextField {
    if (!_passwordTextField) {
        _passwordTextField = ({
            UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(Size_W(50), Size_H(58.5), ScreenW - Size_W(50), Size_H(34))];
            
//            textField.placeholder = @"请输入短信中的验证码";
            textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入密码" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:Font(17)]}];
            
            textField.delegate = self;
            
            textField.clearButtonMode = UITextFieldViewModeWhileEditing;
            textField.tintColor = [UIColor redColor];
            textField.keyboardType = UIKeyboardTypePhonePad;
            textField.tag = 1005;
            [textField addTarget:self action:@selector(respondsToShowLoginButton:) forControlEvents:UIControlEventEditingChanged];
            
            textField;
        });
    }
    
    return _passwordTextField;
}

@end
